package com.business.user.listener;

import com.alibaba.fastjson.JSONObject;
import com.business.common.enums.RabbitMqConstant;
import com.business.redis.constant.RedisKeyConstant;
import com.business.redis.utils.RedisUtil;
import com.business.user.service.UserDataQuantityService;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * 监听用户数量修改
 */
@Service
public class UserDataQuantityListener {

    private Logger logger = LoggerFactory.getLogger(UserDataQuantityListener.class);

    @Autowired
    private UserDataQuantityService userDataQuantityService;

    /**
     * 监听 发送修改用户数量统计队列
     *
     * @param message
     * @param channel
     */
    @RabbitListener(queues = RabbitMqConstant.SEND_USER_DATA_QUANTITY)
    public void sendVerificationCodeListener(Message message, Channel channel) throws IOException {
        JSONObject params = JSONObject.parseObject(new String(message.getBody()));
        logger.info(RabbitMqConstant.SEND_USER_DATA_QUANTITY + " 接收参数执行开始,参数： " + params);
        if (null == params) {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            return;
        }
        try {
            Integer quantity = params.getInteger("quantity");
            String module = params.getString("module");
            Integer userId = params.getInteger("userId");
            userDataQuantityService.addNumber(userId, quantity, module);
            String key = String.format(RedisKeyConstant.USER_DATA_QUANTITY_QUERY_BY_USER, userId);
            //删除缓存
            RedisUtil.delValue(key);
            logger.info(RabbitMqConstant.SEND_USER_DATA_QUANTITY + " 执行结束");
        } finally {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }
    }
}
